angular.module('liemallfodder')
  .controller('MaterialDetailCtrl', function ($scope, $stateParams, Loading, ApiManager, MaterialApi, WechatApi) {
    var signature = null;
    $scope.material = null;

    var requestWechatSign = function () {
      WechatApi.getSignPackage(function (result) {
        if (ApiManager.hasError(result)) {
          return;
        }
        signature = result.data;
      }, function (error) {
        ApiManager.showError(error);
      });
    };

    var requestMaterialDetail = function () {
      Loading.show('正在加载');
      var material_id = $stateParams.material_id;
      if (material_id < 0) {
        Toast.show('错误的id');
        return;
      }

      MaterialApi.materialDetail(material_id, function (result) {
        Loading.hide();
        if (ApiManager.hasError(result)) {
          return;
        }
        $scope.material = result.data;
        $scope.material.content = result.data.content.replace(/<img/g, '<img ng-click="onImageClick($event)"');
        console.log($scope.material);
      }, function (error) {
        Loading.hide();
        ApiManager.showError(error);
      });
    };

    $scope.onImageClick = function (event) {
      var imageUrl = event.target.currentSrc;
      previewImage(imageUrl);
    };

    var previewImage = function (url) {
      if (signature == null) {
        return;
      }

      var urls = [url];
      WechatApi.previewImage(signature,urls);
    };


    requestWechatSign();
    requestMaterialDetail();
  })
  .directive('materialDetail', function ($compile, $parse) {
    return {
      link: function (scope, element, attr) {
        scope.$watch(attr.materialDetail, function () {
          element.html($parse(attr.materialDetail)(scope));
          $compile(element.contents())(scope);
        }, true);
      }
    }
  });
